import sqlalchemy
from sqlalchemy import Column, String, Integer, DateTime, extract
from utils.sql.db import session, Base
import time
from utils.sql.app.user import get_userinfo
from utils.sql.app.ganger import get_ganger


# 定义User对象:
class Man_day(Base):
    # 表的名字:
    __tablename__ = 'man_day'

    # 表的结构:
    id = Column(Integer(), primary_key=True, default=None)
    user_id = Column(String(20), default='')
    job_date = Column(String(255), default='')
    start_time = Column(String(20), default='')
    end_time = Column(String(20), default='')
    working_days = Column(String(20), default='')
    half_time = Column(String(20), default='')
    over_time = Column(String(20), default='')
    man_hour = Column(Integer(), default='')
    money_day = Column(Integer(), default='')
    overtime_pay = Column(Integer(), default='')
    job_location = Column(String(20), default='')
    ganger_id = Column(String(20), default='')
    create_time = Column(String(20), default=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


# 添加工天
def insert_record(data, user_id):
    try:
        is_man_day = session.query(Man_day).filter(Man_day.user_id == user_id, Man_day.job_date == data['job_date']).all()
        if len(is_man_day) > 0:
            return {
                "code": 405,
                "data": data['job_date'],
                "message": "数据已添加"
            }
        else:
            user = get_userinfo(user_id)
            if user['code'] == 200:
                # 创建新record对象:
                new_user = Man_day(
                    user_id=user_id,
                    job_date=data['job_date'],
                    start_time=data['start_time'],
                    end_time=data['end_time'],
                    working_days=data['working_days'],
                    half_time=data['half_time'],
                    over_time=data['over_time'],
                    man_hour=data['man_hour'],
                    money_day=data['money_day'],
                    overtime_pay=data['overtime_pay'],
                    ganger_id=user['data'].ganger_id,
                    job_location=user['data'].job_location,
                    create_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                )
                # 添加到session:
                session.add(new_user)
                # 提交即保存到数据库:
                session.commit()
                return {
                    "code": 200,
                    "data": "",
                    "message": "数据添加成功"
                }
    except sqlalchemy.exc.IntegrityError as e:
        return {
            "code": 201,
            "data": e,
            "message": "数据添加失败"
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# 查询工天列表
# 用于分页查询--每页数量
size = 15


def record_list(year, month, user_id, current=1):
    record = None
    try:
        # 创建Query查询，filter是where条件，最后调用one()返回唯一行，如果调用all()则返回所有行:
        # session.query(Post).fitler(extract('month', Post.created) == 7).all()

        lists = session.query(Man_day).order_by(Man_day.id.desc()).filter(Man_day.user_id == user_id)
        if lists:
            start = (current - 1) * size
            end = current * size
            # if query:
            lists = lists.filter(extract('year', Man_day.job_date) == year, extract('month', Man_day.job_date) == month)
            # print(lists, 2)
            record = lists.slice(start, end).all()
            for i in record:
                print(i.ganger_id)
                ganger = get_ganger(i.ganger_id, user_id)
                if ganger['code'] == 200:
                    i.ganger_name = ganger['data'].ganger_name
            return {
                "code": 200,
                "data": record,
                "message": '查询成功'
            }
    except sqlalchemy.exc.NoResultFound as e:
        return {
            "code": 201,
            "data": e,
            "message": '查询失败'
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# 查询单个工天
def record_one(id, user_id):
    try:
        # 创建Query查询，filter是where条件，最后调用one()返回唯一行，如果调用all()则返回所有行:
        # session.query(Post).fitler(extract('month', Post.created) == 7).all()

        lists = session.query(Man_day).filter(Man_day.user_id == user_id, Man_day.id == id).one()

        if lists:
            return {
                "code": 200,
                "data": lists,
                "message": '查询成功'
            }
    except sqlalchemy.exc.NoResultFound as e:
        return {
            "code": 201,
            "data": e,
            "message": '查询失败'
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()


# 修改单个工天
def update_records(data, user_id):
    try:
        query = session.query(Man_day).filter(Man_day.id == data['id'], Man_day.user_id == user_id)  # 添加合适的过滤条件
        result = query.all()
        for item in result:
            # 将属性值设置为新的值
            item.start_time = data['start_time']
            item.end_time = data['end_time']
            item.half_time = data['half_time']
            item.over_time = data['over_time']
            item.man_hour = data['man_hour']
            item.money_day = data['money_day']
            item.overtime_pay = data['overtime_pay']
        # 提交事务
        session.commit()
        return {
            "code": 200,
            "data": '',
            "message": '操作成功'
        }
    except sqlalchemy.exc.NoResultFound as e:
        return {
            "code": 201,
            "data": e,
            "message": '操作失败'
        }
        session.rollback()
        raise
    finally:
        # 关闭session:
        session.close()
